package com.wormpex.data.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

//@Component
public class QuartzInitListener implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(QuartzInitListener.class);

    /**防止定时任务被加载多次.*/
    private static AtomicInteger INIT_LOCK = new AtomicInteger(0);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        if (INIT_LOCK.incrementAndGet() > 1) {
            logger.info("任务已经加载过,请勿重新加载...");
            return;
        }

        Resource resource = applicationContext.getResource("classpath:task.file");
        if (!resource.exists()) {
            logger.info("定时任务没有启动");
            return;
        }
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(applicationContext);
        context.setConfigLocations("classpath:spring/spring-job.xml");
        context.refresh();
        logger.info("定时任务启动");
    }
}